package com.example.partiu;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class EditarMateriaActivity extends Activity {
	BancoDeDados dbHelper = null;
	 SQLiteDatabase db = null;
	 String nome;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editar_materia);
		try{
			dbHelper = new BancoDeDados(getApplicationContext());
		}catch(Exception ex){
			new AlertDialog.Builder(this).setMessage(ex.getMessage()).setPositiveButton("OK", null).show();
		}
		//Nome da materia selecionada 
		Intent intent = getIntent();
		nome = intent.getStringExtra("nome");
		TextView text = (TextView) findViewById(R.id.textView1);
		text.setText(""+nome);
		
		//Identifica os campos para serem atualizados
		EditText edit = (EditText) findViewById(R.id.editText1);
		EditText edit2 = (EditText) findViewById(R.id.editText2);
		EditText edit3 = (EditText) findViewById(R.id.editText3);
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT DIASEMANA, HORARIO, FPERMITIDAS FROM MATERIA WHERE NOME = '" + nome + "'", null);
		while (cursor.moveToNext()){
			edit.setText(""+cursor.getString(cursor.getColumnIndex("DIASEMANA")));
			edit2.setText(""+cursor.getString(cursor.getColumnIndex("HORARIO")));
			edit3.setText(""+cursor.getString(cursor.getColumnIndex("FPERMITIDAS")));
		}
		db.close();
		dbHelper.close();
		cursor.close();
	}
	
	//Faz o update da materia selecionada e chama a activity materia 
		public void salvar(View view){
			EditText edit = (EditText) findViewById(R.id.editText1);
			EditText edit2 = (EditText) findViewById(R.id.editText2);
			EditText edit3 = (EditText) findViewById(R.id.editText3);
			String diasemana = edit.getText().toString();
			String horario = edit2.getText().toString();
			String fpermitidas = edit3.getText().toString();
			
			db = dbHelper.getWritableDatabase();
			db.execSQL("UPDATE MATERIA SET DIASEMANA = '" + diasemana + "', HORARIO = '" + horario + "', FPERMITIDAS = '" + fpermitidas + "' WHERE NOME = '" + nome + "'");
			db.close();
			dbHelper.close();
			
			Intent intent3 = new Intent(this, MateriaActivity.class);
			intent3.putExtra("posicao", nome);
			startActivity(intent3);
		}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.editar_materia, menu);
		return true;
	}

}
